package com.ziq.zcamp.dialog.share

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Bitmap
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.FrameLayout
import android.widget.Toast
import com.facebook.imagepipeline.request.ImageRequest
import com.gmlive.camp.dialog.share.SharePicCacheInterface
import com.ziq.base.extension.dp
import com.ziq.zcamp.R
import com.ziq.zcamp.api.request.common.MiniACodeParam
import com.ziq.zcamp.bean.activities.ActivitiesInfo
import com.ziq.zcamp.constant.H5Url
import com.ziq.zcamp.databinding.LayoutSharePicCacheActivitiesBinding
import com.ziq.zcamp.manager.GlobalContextManager
import com.ziq.zcamp.manager.UserManager
import com.ziq.zcamp.util.ImageUtil
import com.ziq.zcamp.util.StorageUtil
import com.ziq.zcamp.util.blurry.Blurry
import com.ziq.zcamp.util.io.IOUtils
import java.io.FileOutputStream
import java.text.DecimalFormat

class SharePicCacheLayoutActivity @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr), SharePicCacheInterface {

    var binding : LayoutSharePicCacheActivitiesBinding = LayoutSharePicCacheActivitiesBinding.inflate(LayoutInflater.from(context), this, true)

    var imageList = mutableListOf<String>()
    var way = ""

    var activitiesInfo : ActivitiesInfo? = null
    val miniPagePath = "subpages/community/activity-detail/index"

    private val uidSuffix by lazy{
        val id = UserManager.instance.userInfo.value?.id.toString()
        if (id.isEmpty()){
            ""
        }else{
            "&shareuid=${id}"
        }
    }

    @SuppressLint("SetTextI18n")
    fun setActivityData(data: ActivitiesInfo){
        activitiesInfo = data
        way = "activity"

        data.images?.let {
            if (it.isNotEmpty()){
                ImageUtil.updateImageFromNetwork(binding.ivActivitiesPoster,it[0].url?:"", ImageRequest.CacheChoice.DEFAULT)

                ImageUtil.getBitmap(0, it[0].url,ImageUtil.imageMaxSize, ImageUtil.imageMaxSize, ImageUtil.imageMaxSize) { _, bitmap ->
                    if (ImageUtil.isBitmapAvailable(bitmap)) {
                        Blurry.with(context)
                            .radius(10)
                            .sampling(8)
                            .color(resources.getColor(R.color.black_translucent_60))
                            .from(bitmap)
                            .into(binding.vMaskActivityInfo)
                    }
                }
            }
        }
        binding.tvActivitiesName.text = data.title
        if (data.start_show_time != null && data.end_show_time!= null){
            if (data.start_show_time.equals(data.end_show_time)){
                binding.tvActivitiesTime.text = "${data.start_show_time}"
            }else{
                binding.tvActivitiesTime.text = "${data.start_show_time}-${data.end_show_time}"
            }
        }else if (data.start_show_time!=null){
            binding.tvActivitiesTime.text = "${data.start_show_time}"
        }else{
            binding.tvActivitiesTime.text = "--:--"
        }
        binding.tvActivitiesPlace.text = data.location_addr
        if (!data.price_range.isNullOrEmpty() && data.free_type != 1){
            val min = data.price_range?.minOrNull()
            val string = DecimalFormat("0.00").format((min?:0) / 100f)
            binding.tvActivitiesPrice.text =  "￥$string 起"
        }else if ( data.free_type == 1){
            binding.tvActivitiesPrice.text =  "免费"
        }else{
            binding.tvActivitiesPrice.text =  ""
        }
        data.related_camp.let {
            if (it!=null && !it.isInfoEmpty()){
                binding.groupCamp.visibility = View.VISIBLE
                binding.tvActivitiesCamp.text = it.name
            }else{
                binding.groupCamp.visibility = View.GONE
            }
        }
        data.organizer.let {
            if (it!=null){
                binding.llActivitiesSponsor.visibility = View.VISIBLE
                ImageUtil.updateImageFromNetwork(binding.ivActivitiesHeadPortrait,it.portrait, ImageRequest.CacheChoice.DEFAULT)
                binding.tvActivitiesUserName.text = it.nick
            }else{
                binding.llActivitiesSponsor.visibility = View.GONE
            }
        }

        data.vr.let {
            if (it != null && it.exist_vr == true){
                binding.llActivitiesVr.visibility = View.VISIBLE
            }else{
                binding.llActivitiesVr.visibility = View.GONE
            }
        }


        getSanCode(finish = { minCodeUrl, bitmap ->
            if(minCodeUrl.isNotEmpty()){
                imageList.add(minCodeUrl)
            }
            isScanCodeSuccess = true
        })

    }

    var isScanCodeSuccess = false
    fun getSanCode(finish: ((minCodeUrl:String, bitmap: Bitmap?) -> Unit)? = null){
        val url = "H5_APP_HOST/#/subpages/community/activity-detail/index/?id=${activitiesInfo?.id?:""}&from=2${uidSuffix}"
        ShareUtil.getSanCode(MiniACodeParam().apply {
            is_hyaline = true
            page = miniPagePath
            scene = "id=${activitiesInfo?.id}&from=1${uidSuffix}&share_cv="
            width = 280.toString()
        }, url,  onSuccess = { minCodeUrl:String, bitmap: Bitmap->
            binding.qrCode.post {
                binding.qrCode.setImageBitmap(bitmap)
            }
            finish?.invoke(minCodeUrl, bitmap)
            if(minCodeUrl.isNotEmpty()){
                binding.qrCodeBottomTxt.text = "识别小程序码 阅读完整内容"
            } else {
                binding.qrCodeBottomTxt.text = "识别二维码 阅读完整内容"
            }
        }, onFail = {
            finish?.invoke("", null)
        })
    }

    /**
     * 图片加载完成
     */
    override fun checkPictureBitmap(action : ()->Unit){
        val length = imageList.size
        var index = -1
        fun callback(){
            index++
            if(index < length){
                val url = imageList[index]
                ImageUtil.getBitmap(0, url, 0, 0) { _, _ ->
                    callback()
                }
            } else {
                action.invoke()
            }
        }
        if(isScanCodeSuccess){
            callback()
        } else {
            getSanCode(finish = { minCodeUrl, bitmap->
                callback()
            })
        }
    }

    override fun getMiniProgramPath(): String {
        if(activitiesInfo != null){
            return "$miniPagePath?id=${activitiesInfo?.id}&from=1${uidSuffix}"
        }
        return "/pages/community/activity-detail/index"
    }

    /**
     * 完整卡片
     */
    override fun getTotalLayoutBitmap() : Bitmap?{
        val b = activitiesInfo?.related_camp?.isInfoEmpty()
        val height = GlobalContextManager.getResources().getDimensionPixelSize(R.dimen.dimens_dip_578) - (if(b==true){50.dp}else{0})
        return ImageUtil.convertViewToBitmap(binding.root,
            GlobalContextManager.getResources().getDimensionPixelSize(R.dimen.dimens_dip_375),
            height)
    }

    /**
     * 小程序分享标题
     */
    override fun getTitleForMiniProgram() : String{
        var content = ""
        if(activitiesInfo != null ){
            if(activitiesInfo?.title?.isNotEmpty() == true){
                content = "${activitiesInfo?.title}"
            }
        }
        return content
    }
    /**
     * 小程序分享卡片封面
     */
    override fun getCoverBitmapForMiniProgram(action : (bitmap : Bitmap?)->Unit){
        var pic = ""
        activitiesInfo?.images?.let {
            pic = it[0].url?:""
        }
        ImageUtil.getBitmap(0, pic, 0, 0) { _, bitmap ->
            action.invoke(bitmap)
        }
    }
    /**
     * 复制链接
     */
    override fun getLinkTxt() : String{
        if(activitiesInfo != null){
            val url = "${H5Url.ACTIVITY_DETAILS.url}?id=${activitiesInfo?.id?:""}&from=1"
            return if (UserManager.instance.userInfo.value != null){
                "${UserManager.instance.userInfo.value?.nick_name}分享了一个露营活动给你，快来看看吧\n $url"
            }else{
                "觅野Camp分享了一个露营活动给你，快来看看吧\n $url"
            }
        }
        return ""
    }

    /**
     * 保存到本地
     */
    override fun onSavePicToLocal(source:String, finish:()->Unit){
        checkPictureBitmap {
            savePicToLocal(source,getTotalLayoutBitmap())
            finish()
        }
    }

    private fun savePicToLocal(source:String,bitmap : Bitmap?){
        try {
            if(bitmap != null){
                val path = StorageUtil.getPictureFileWith("camp_share_${way}_${System.currentTimeMillis()}.png")
                var fos: FileOutputStream? = null
                try {
                    fos = FileOutputStream(path)
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos)
                    fos.flush()
                } catch (e: Exception) {
                } finally {
                    IOUtils.close(fos)
                }
                if (path.exists() && path.length() > 0) {
                    ImageUtil.insertImageToAlbum(context, path.absolutePath)
                    val msg = GlobalContextManager.getString(R.string.share_save_success_toast)
                    Toast.makeText(context, msg, Toast.LENGTH_SHORT).show()
                } else {
                    val msg = GlobalContextManager.getString(R.string.share_save_fail_toast)
                    Toast.makeText(context, msg, Toast.LENGTH_SHORT).show()
                }
            }
        } catch (ignore: Exception) {
            val msg = GlobalContextManager.getString(R.string.share_save_fail_toast)
            Toast.makeText(context, msg, Toast.LENGTH_SHORT).show()
        }
    }
}